using System;
using System.Collections;
using System.Web.UI;
using System.Web.UI.WebControls;
using PHSRAG.Insight21.Common.Pages;
using PHSRAG.Insight21.Context;
using PHSRAG.Insight21.InsightUtilities;
using PHSRAG.Insight21.Policy;
using PHSRAG.Insight21.SearchContext;
using PHSRAG.Security.Enumerations;
using PHSRAG.Utility;

namespace PHSRAG.Insight21.Home
{
    /// <summary>
    /// Summary description for Home.
    /// </summary>
    public partial class HomePage : BasePage
    {
        #region Instance Variables (Private)

        // Image buttons to provide easy navigation access to individual modules
        private ImageButton adminLink;
        private ImageButton agreementsLink;
        private ImageButton animalsLink;
        private ICachePolicy cachePolicy;
        private ImageButton clinicalTrialsLink;
        private ImageButton coiLink;
        private ImageButton humansLink;
        private ImageButton personnelLink;
        private ImageButton purchasingLink;
        private ImageButton reportsLink;

        #endregion

        #region Overrides

        /// <summary>
        /// Create all child controls as normal and, additionally, generate the module description section.
        /// </summary>
        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            UserContext userContext = cachePolicy.GetCachedObject(UserContext.CacheKey) as UserContext;

            if (userContext != null)
            {
                int moduleRoleBitmask = userContext.ModuleRoleBitmask;
                int moduleBitmask = userContext.ModuleBitmask;

                moduleSelectionTable.Attributes["cellspacing"] = "15";

                TableRow row = new TableRow();
                moduleSelectionTable.Rows.Add(row);

                TableCell instructionCell = new TableCell();
                row.Cells.Add(instructionCell);
                instructionCell.CssClass = "Label";
                instructionCell.Attributes["colspan"] = "2";
                instructionCell.Controls.Add(new LiteralControl("<nobr>The following modules are associated with your profile:</nobr>"));

                ArrayList cells = new ArrayList();

                // if the user has access to the Agreements Module, add the description and link button
                if (((moduleBitmask & (int) ModuleBit.Agreements) != 0))
                {
                    TableCell agreementsCell = new TableCell();
                    agreementsCell.Controls.Add(new LiteralControl("<nobr><font class=\"DescriptionLabel\"><nobr>Agreements</nobr></font></nobr><br>"));
                    agreementsCell.Controls.Add(new LiteralControl(Settings.GetKeyValue("Home.AgreementsDescription", string.Empty) + "<br>"));
                    agreementsCell.Attributes["width"] = "50%";

                    agreementsLink = new ImageButton();
                    agreementsLink.CommandName = Constants.Modules.Agreements;
                    agreementsLink.ImageUrl = "../Images/b_gotoagr.gif";
                    agreementsLink.CommandArgument = Settings.GetKeyValue("Header.AgreementsURL", string.Empty);
                    agreementsLink.CausesValidation = false;

                    agreementsCell.Controls.Add(agreementsLink);

                    cells.Add(agreementsCell);

                    CreateDocumentationLink(Constants.Modules.Agreements);
                }

                // if the user has access to the Humans Module, add the description and link button
                if (((moduleBitmask & (int) ModuleBit.Humans) != 0))
                {
                    TableCell humansCell = new TableCell();
                    humansCell.Controls.Add(new LiteralControl("<nobr><font class=\"DescriptionLabel\"><nobr>Humans (eIRB)</nobr></font></nobr><br>"));
                    humansCell.Controls.Add(new LiteralControl(Settings.GetKeyValue("Home.HumansDescription", string.Empty) + "<br>"));
                    humansCell.Attributes["width"] = "50%";

                    humansLink = new ImageButton();
                    humansLink.CommandName = Constants.Modules.Humans;
                    humansLink.ImageUrl = "../Images/b_gotohumans.gif";
                    humansLink.CommandArgument = Settings.GetKeyValue("Header.HumansURL", string.Empty);
                    humansLink.CausesValidation = false;

                    humansCell.Controls.Add(humansLink);

                    cells.Add(humansCell);

                    CreateDocumentationLink(Constants.Modules.Humans);

                    /*eIRB Link*/

                    CreateDocumentationLink(Constants.Modules.eIRB);
                }

                // if the user has access to the Humans Module, add the description and link button
                if (((moduleBitmask & (int) ModuleBit.Animals) != 0))
                {
                    TableCell animalsCell = new TableCell();
                    animalsCell.Controls.Add(new LiteralControl("<nobr><font class=\"DescriptionLabel\"><nobr>Animals (eIACUC)</nobr></font></nobr><br>"));
                    animalsCell.Controls.Add(new LiteralControl(Settings.GetKeyValue("Home.AnimalsDescription", string.Empty) + "<br>"));
                    animalsCell.Attributes["width"] = "50%";

                    animalsLink = new ImageButton();
                    animalsLink.CommandName = Constants.Modules.Animals;
                    animalsLink.ImageUrl = "../Images/b_gotoanimals.gif";
                    animalsLink.CommandArgument = Settings.GetKeyValue("Header.AnimalsURL", string.Empty);
                    animalsLink.CausesValidation = false;

                    animalsCell.Controls.Add(animalsLink);

                    cells.Add(animalsCell);

                    CreateDocumentationLink(Constants.Modules.Animals);
                }

                // if the user has access to the Clinical Trials Module, add the description and link button
                if (((moduleBitmask & (int) ModuleBit.ClinicalTrials) != 0))
                {
                    TableCell clinicalTrailsCell = new TableCell();
                    clinicalTrailsCell.Controls.Add(new LiteralControl("<nobr><font class=\"DescriptionLabel\"><nobr>Clinical Trials</nobr></font></nobr><br>"));
                    clinicalTrailsCell.Controls.Add(new LiteralControl(Settings.GetKeyValue("Home.ClinicalTrialsDescription", string.Empty) + "<br>"));
                    clinicalTrailsCell.Attributes["width"] = "50%";

                    clinicalTrialsLink = new ImageButton();
                    clinicalTrialsLink.CommandName = Constants.Modules.ClinicalTrials;
                    clinicalTrialsLink.ImageUrl = "../Images/b_gotoclintrials.gif";
                    clinicalTrialsLink.CommandArgument = Settings.GetKeyValue("Header.ClinicalTrialsURL", string.Empty);
                    clinicalTrialsLink.CausesValidation = false;

                    clinicalTrailsCell.Controls.Add(clinicalTrialsLink);

                    cells.Add(clinicalTrailsCell);

                    CreateDocumentationLink(Constants.Modules.ClinicalTrials);
                }

                // if the user has access to the Personnel Module, add the description and link button
                if (((moduleBitmask & (int) ModuleBit.Personnel) != 0))
                {
                    TableCell personnelCell = new TableCell();
                    personnelCell.Controls.Add(new LiteralControl("<nobr><font class=\"DescriptionLabel\"><nobr>Personnel</nobr></font></nobr><br>"));
                    personnelCell.Controls.Add(new LiteralControl(Settings.GetKeyValue("Home.PersonnelDescription", string.Empty) + "<br>"));
                    personnelCell.Attributes["width"] = "50%";

                    personnelLink = new ImageButton();
                    personnelLink.CommandName = Constants.Modules.Personnel;
                    personnelLink.ImageUrl = "../Images/b_gotopersonnel.gif";
                    personnelLink.CommandArgument = Settings.GetKeyValue("Header.PersonnelURL", string.Empty);
                    personnelLink.CausesValidation = false;

                    personnelCell.Controls.Add(personnelLink);

                    cells.Add(personnelCell);

                    CreateDocumentationLink(Constants.Modules.Personnel);
                }

                // if the user has access to the Purchasing Module, add the description and link button
                if (((moduleBitmask & (int) ModuleBit.Purchasing) != 0))
                {
                    TableCell purchasingCell = new TableCell();
                    purchasingCell.Controls.Add(new LiteralControl("<nobr><font class=\"DescriptionLabel\"><nobr>Purchasing</nobr></font></nobr><br>"));
                    purchasingCell.Controls.Add(new LiteralControl(Settings.GetKeyValue("Home.PurchasingDescription", string.Empty) + "<br>"));
                    purchasingCell.Attributes["width"] = "50%";

                    purchasingLink = new ImageButton();
                    purchasingLink.CommandName = Constants.Modules.Purchasing;
                    purchasingLink.ImageUrl = "../Images/b_gotopurch.gif";
                    purchasingLink.CommandArgument = Settings.GetKeyValue("Header.PurchasingURL", string.Empty);
                    purchasingLink.CausesValidation = false;

                    purchasingCell.Controls.Add(purchasingLink);

                    cells.Add(purchasingCell);

                    CreateDocumentationLink(Constants.Modules.Purchasing);
                }

                // if the user has access to the Conflict Of Interest Module, add the description and link button
                if (((moduleBitmask & (int) ModuleBit.COI) != 0))
                {
                    TableCell coiCell = new TableCell();
                    coiCell.Controls.Add(new LiteralControl("<nobr><font class=\"DescriptionLabel\"><nobr>Conflict of Interest</nobr></font></nobr><br>"));
                    coiCell.Controls.Add(new LiteralControl(Settings.GetKeyValue("Home.COIDescription", string.Empty) + "<br>"));
                    coiCell.Attributes["width"] = "50%";

                    coiLink = new ImageButton();
                    coiLink.CommandName = Constants.Modules.COI;
                    coiLink.ImageUrl = "../Images/b_confofint.gif";
                    coiLink.CommandArgument = Settings.GetKeyValue("Header.CoIURL", string.Empty);
                    coiLink.CausesValidation = false;

                    coiCell.Controls.Add(coiLink);

                    cells.Add(coiCell);

                    CreateDocumentationLink(Constants.Modules.COI);
                }

                // if the user has access to the Reports Module, add the description and link button
                if (((moduleBitmask & (int) ModuleBit.Reporting) != 0))
                {
                    TableCell reportingCell = new TableCell();
                    reportingCell.Controls.Add(new LiteralControl("<nobr><font class=\"DescriptionLabel\"><nobr>Reports</nobr></font></nobr><br>"));
                    reportingCell.Controls.Add(new LiteralControl(Settings.GetKeyValue("Home.ReportsDescription", string.Empty) + "<br>"));
                    reportingCell.Attributes["width"] = "50%";

                    reportsLink = new ImageButton();
                    reportsLink.CommandName = Constants.Modules.Reporting;
                    reportsLink.ImageUrl = "../Images/b_gotoreports.gif";
                    reportsLink.CommandArgument = Settings.GetKeyValue("Header.ReportingURL", string.Empty);
                    reportsLink.CausesValidation = false;

                    reportingCell.Controls.Add(reportsLink);

                    cells.Add(reportingCell);

                    CreateDocumentationLink(Constants.Modules.Reporting);
                }

                // if the user has access to the Admin Module, add the description and link button
                if ((((moduleBitmask & (int) ModuleBit.Admin) != 0)))
                {
                    TableCell adminCell = new TableCell();
                    adminCell.Controls.Add(new LiteralControl("<nobr><font class=\"DescriptionLabel\"><nobr>Admin</nobr></font></nobr><br>"));
                    adminCell.Controls.Add(new LiteralControl(Settings.GetKeyValue("Home.AdminDescription", string.Empty) + "<br>"));
                    adminCell.Attributes["width"] = "50%";

                    adminLink = new ImageButton();
                    adminLink.CommandName = Constants.Modules.Admin;
                    adminLink.ImageUrl = "../Images/b_gotoadmin.gif";
                    adminLink.CausesValidation = false;

                    // If the user is a SysAdmin, KeyGiver, or PI the landing page will be  
                    // User Management (search users) because they can give out access to other users.  
                    // Otherwise, they have access to the Admin module for Humans Management only and the appropriate
                    // landing page is based on their module role bitmask.
                    if ((userContext.IsKeyGiver ||
                        ((moduleRoleBitmask & (int) ModuleRoleBit.SystemAdministrator |
                            (int) ModuleRoleBit.PrincipalInvestigator) != 0)))
                    {
                        adminLink.CommandArgument = Settings.GetKeyValue("Header.AdminURL", string.Empty);
                    }

                    else if (((moduleRoleBitmask & (int) ModuleRoleBit.FormsManager) != 0))
                    {
                        adminLink.CommandArgument =
                            Settings.GetKeyValue("SubNavigation.Admin.Humans.FormsManagementURL", string.Empty);
                    }
                    else if (((moduleRoleBitmask & (int) ModuleRoleBit.ListManager) != 0))
                    {
                        adminLink.CommandArgument =
                            Settings.GetKeyValue("SubNavigation.Admin.Humans.ListRequestURL", string.Empty);
                    }
                    else
                    {
                        adminLink.CommandArgument =
                            Settings.GetKeyValue("SubNavigation.Admin.WorkFlowManagerURL", string.Empty);
                    }

                    adminCell.Controls.Add(adminLink);

                    cells.Add(adminCell);

                    CreateDocumentationLink(Constants.Modules.Admin);
                }

                //Modified the logic to support automatic creation of rows to hold 
                //the table cells created from previous steps.(2 columns per row).
                //Note:This will support addition of new modules without any change in the below loop.

                if (cells.Count > 0)
                {
                    int cellIndex = 1;
                    int cellsCount = cells.Count + 1;

                    // build the first row of up to two module descriptions
                    row = new TableRow();
                    moduleSelectionTable.Rows.Add(row);

                    for (; cellIndex < cellsCount; cellIndex++)
                    {
                        if (cellIndex%2 == 1)
                        {
                            row = new TableRow();
                            moduleSelectionTable.Rows.Add(row);
                            row.VerticalAlign = VerticalAlign.Top;
                            row.Cells.Add(cells[cellIndex - 1] as TableCell);
                        }
                        else if (cellIndex%2 == 0)
                        {
                            row.VerticalAlign = VerticalAlign.Top;
                            row.Cells.Add(cells[cellIndex - 1] as TableCell);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Creates a new table row, with one cell, with a hyperlink in it to point to the 
        /// documentation pdf file.
        /// </summary>
        /// <param name="module"></param>
        private void CreateDocumentationLink(string module)
        {
            HyperLink documentationLink = new HyperLink();
            documentationLink.Target = "_blank";

            TableRow documentationLinkRow = new TableRow();
            TableCell documentationLinkCell = new TableCell();

            documentationLink.NavigateUrl = module.Equals("eIRB") ? ResolveUrl("~/Home/eIRBSelections.aspx") : ResolveUrl(string.Format("~/Documentation/Insight User Manual - {0}.pdf", module));

            documentationLink.Text = string.Format("{0} Module", module);
            documentationLinkCell.Controls.Add(new LiteralControl("<img src=\"../Images/login_arrow.gif\" />&nbsp;"));
            documentationLinkCell.Controls.Add(documentationLink);
            documentationLinkRow.Cells.Add(documentationLinkCell);
            documentationLinks.Controls.Add(documentationLinkRow);
        }

        /// <summary>
        /// Invoked when an event is raised by a child control.
        /// </summary>
        /// <param name="source">Reference to the child control that raised the event</param>
        /// <param name="e">Argument associated with the event</param>
        /// <returns>True if the event was handle by this method; false otherwise</returns>
        protected override bool OnBubbleEvent(object source, EventArgs e)
        {
            // Events raised only by link/image buttons are handled. The name of the button which raised the event is stored
            // in the session and the associated URL is navigated to. The name stored in the session is used during page
            // load to highlight the link which was last clicked.
            bool handled = false;
            if (e is CommandEventArgs)
            {
                string commandName = null, targetPage = null;
                if (source is ImageButton)
                {
                    ImageButton button = (ImageButton) source;
                    commandName = button.CommandName;
                    targetPage = button.CommandArgument;
                }

                if ((commandName != null) && (targetPage != null))
                {
                    CommandEventHandler handler = (CommandEventHandler) Events["Navigate"];
                    if (handler != null)
                    {
                        handler(this, new CommandEventArgs(commandName, null));
                    }

                    header.ModuleName = commandName;

                    //Whenever the header nav links are selected, the search level must be set to Summary level.
                    CommonSearchContext searchContext = (CommonSearchContext) cachePolicy.GetCachedObject(CommonSearchContext.CacheKey);
                    if (searchContext != null)
                    {
                        searchContext.CurrentLevel = SearchCriteria.Level.Summary;
                    }

                    Page.Response.Redirect(targetPage);
                    handled = true;
                }
            }
            return handled;
        }

        #endregion

        #region Page Load

        protected void OnPageLoad(object sender, EventArgs e)
        {
            EnableViewState = false;

            string messageText = "";
            UserContext userContext = cachePolicy.GetCachedObject(UserContext.CacheKey) as UserContext;
            if (userContext != null)
            {
                if (userContext.IsFirstTimeUser())
                {
                    messageText = String.Concat(messageText, "This is your first successful login.");
                }
                else
                {
                    messageText = String.Concat(messageText,
                        "Welcome to Insight, ",
                        userContext.FirstName,
                        " ",
                        userContext.LastName);
                }
            }

            messageLabel.Text = messageText;

            Hashtable dictionary = (Hashtable) Session[Keys.IncomingDataKey];

            if (dictionary != null)
            {
                annunciator.Message = (string) dictionary[Keys.ErrorKey];
            }
        }

        #endregion

        #region Web Form Designer generated code

        /// <summary>
        /// Initialize the page. Retrieve the cache policy from the application cache.
        /// </summary>
        /// <param name="e">Argument associated with the event</param>
        protected override void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);

            cachePolicy = (Policy.ICachePolicy) Session[Policy.Names.CachePolicyKey];
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.ID = "Home";
            this.Load += new System.EventHandler(this.OnPageLoad);
        }

        #endregion
    }
}